package threads;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class TestTaobaoThread2s_CountDownLatch {
    private final static TestTaobaoThread2s_CountDownLatch t = new TestTaobaoThread2s_CountDownLatch();
    private static CountDownLatch latch = new CountDownLatch(1);
    private static CountDownLatch latch2 = new CountDownLatch(1);
    private volatile List<String> list = Collections.synchronizedList(new ArrayList<>());

    public void add(String o) {
        list.add(o);
    }

    public int size() {
        return list.size();
    }

    public static void main(String[] args) {
        new Thread(() -> {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            latch2.countDown();
            System.out.println("t2 end.");
        }, "t2").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                t.add(String.valueOf(i));
                System.out.println("add " + i);
                if (i == 5) {
                    latch.countDown();;
                    try {
                        latch2.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "t1").start();
    }
}
